/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.longview.io.modules.app.web;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.longview.io.common.mapper.JsonMapper;
import com.longview.io.common.persistence.Page;
import com.longview.io.common.utils.DateUtils;
import com.longview.io.common.utils.ImageHeler;
import com.longview.io.common.utils.MapAreaUtils;
import com.longview.io.common.utils.SmsUtils;
import com.longview.io.common.utils.UploadUtils;
import com.longview.io.common.web.BaseController;
import com.longview.io.modules.analysis.entity.Coordinates;
import com.longview.io.modules.analysis.entity.GrassAnalysis;
import com.longview.io.modules.analysis.service.GrassAnalysisService;
import com.longview.io.modules.appversion.entity.SysAppVersion;
import com.longview.io.modules.appversion.service.SysAppVersionService;
import com.longview.io.modules.grassbelt.entity.SysGrassBelt;
import com.longview.io.modules.grassbelt.service.SysGrassBeltService;
import com.longview.io.modules.grasscoverage.service.GrassCoverageService;
import com.longview.io.modules.grassfeedback.entity.GrassFeedback;
import com.longview.io.modules.grassfeedback.service.GrassFeedbackService;
import com.longview.io.modules.grassimgs.entity.GrassImgs;
import com.longview.io.modules.grassimgs.service.GrassImgsService;
import com.longview.io.modules.grassinfo.entity.UserGrasslandInfo;
import com.longview.io.modules.grassinfo.service.UserGrasslandInfoService;
import com.longview.io.modules.grasstype.entity.GrassType;
import com.longview.io.modules.grasstype.service.GrassTypeService;
import com.longview.io.modules.livestockinfo.entity.UserLivestockInfo;
import com.longview.io.modules.livestockinfo.service.UserLivestockInfoService;
import com.longview.io.modules.sms.entity.SmsInfo;
import com.longview.io.modules.sms.service.SmsInfoService;
import com.longview.io.modules.sys.entity.Area;
import com.longview.io.modules.sys.entity.Dict;
import com.longview.io.modules.sys.entity.User;
import com.longview.io.modules.sys.service.AreaService;
import com.longview.io.modules.sys.service.DictService;
import com.longview.io.modules.sys.utils.DictUtils;
import com.longview.io.modules.userinfo.entity.UserInfo;
import com.longview.io.modules.userinfo.service.UserInfoService;

import freemarker.core.ReturnInstruction.Return;

/**
 * 短信验证码Controller
 * 
 * @author 张飞
 * @version 2017-03-27
 */
@Controller
@RequestMapping(value = "${frontPath}/app")
public class AppController extends BaseController {
	private static Logger logger = LoggerFactory.getLogger(AppController.class);
	@Autowired
	private SmsInfoService smsInfoService;
	// 前台用户信息
	@Autowired
	private UserInfoService userInfoService;
	// 草原信息
	@Autowired
	private UserGrasslandInfoService userGrasslandInfoService;
	// 畜牧信息
	@Autowired
	private UserLivestockInfoService userLivestockInfoService;
	// 地区
	@Autowired
	private AreaService areaService;
	// 字典
	@Autowired
	private DictService dictService;
	// 草地分析
	@Autowired
	private GrassAnalysisService grassAnalysisService;
	// 草原带
	@Autowired
	private SysGrassBeltService sysGrassBeltService;

	@Autowired
	private GrassTypeService grassTypeService;
	@Autowired
	private GrassCoverageService grassCoverageService;

	@Autowired
	private GrassImgsService grassImgsService;

	@Autowired
	private SysAppVersionService sysAppVersionService;

	@Autowired
	private GrassFeedbackService grassFeedbackService;

	// 返回数据公告参数
	public JSONObject jserrorCode = new JSONObject();

	public final String REGISTER_CODE = "10001";
	public final String USER_EDIT_CODE = "10002";
	public final String USER_VIEW_CODE = "10003";
	public final String LOGIN_CODE = "10004";
	public final String EDIT_PASS_CODE = "10005";
	public final String RESET_PASS_CODE = "10006";
	public final String SMS_CODE = "10007";

	public final String PASTURE_CODE = "10008";
	public final String LIVESTOCK_CODE = "10009";
	public final String LIVESTOCK_EDIT_CODE = "10010";
	public final String PASTURE_EDIT_CODE = "10011";
	public final String IMG_EDIT_CODE = "10012";

	public final String ANALYSIS_CODE = "10013";
	public final String ANALYSIS_Result_CODE = "10014";
	public final String ANALYSIS_Result_LIST_CODE = "10015";

	public final String NATION_CODE = "10051";
	public final String LIVESTOCK_TYPE_LIST_CODE = "10052";
	public final String ADDRESS_LIST_CODE = "10053";
	public final String GRASSLIST_CODE = "10054";

	public final String UP_CODE = "10061";
	public final String DISTANCE_CODE = "10062";

	public final String APP_VERSION_CODE = "10071";

	public final String HIS_ANALYSIS_CODE = "10072";
	public final String ANALYSIS_IMAGES = "10073";

	public final String FEEDBACK = "10074";

	public static String Fileurl = "file/userimg/app/User/";

	private final Md5PasswordEncoder md5encoder = new Md5PasswordEncoder();
	// 亩转化为平米
	private double muDwei = 666.7;

	static class loction {
		String lon;
		String lat;

		public String getLon() {
			return lon;
		}

		public void setLon(String lon) {
			this.lon = lon;
		}

		public String getLat() {
			return lat;
		}

		public void setLat(String lat) {
			this.lat = lat;
		}
	}

	/***
	 * app接口
	 */
	@RequestMapping(value = "api", method = { RequestMethod.POST, RequestMethod.GET })
	public @ResponseBody String api(@RequestBody Map<String, Object> params, HttpServletResponse response) {
		Map<String, String> returnmap = new HashMap<String, String>();

		String msgtype = params.get("msgtype").toString();
		// 登录接口
		if (msgtype.compareTo(LOGIN_CODE) == 0) {
			JSONObject jsonPage = (JSONObject) params;
			User user = jsonPage.toJavaObject(User.class);
			return renderString(response, user);
		}
		return renderString(response, returnmap);
	}

	/**
	 * API接口总接口
	 * 
	 * @param state
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "", method = RequestMethod.POST)
	@ResponseBody
	public String post(String json, HttpServletRequest request) {

		try {
			JSONObject datajson = new JSONObject();
			String state = StringEscapeUtils.unescapeHtml4(json);
			logger.info("接收报文:" + state);
			// 初始化返回参数
			jserrorCode = new JSONObject();
			// 02a3f0772fcca9f415adc990734b45c6f059c7d33ee28362c4852032
			// state=request.getParameter("state");
			// 解析传递过来的json
			JSONObject jsStr = JSONObject.parseObject(state); // 将字符串{“id”：1}
			// 判断是否有需要的值
			// RequestParam(value = "file", required = false) MultipartFile file
			boolean value = jsStr.containsKey("msgtype");
			String msgtype = "";
			// 判断格式 是否正确 。如果不存在 返回格式错误
			if (!value) {
				jserrorCode.put("errorCode", 1);
				jserrorCode.put("errorMessage", "格式错误");
				jserrorCode.put("data", datajson);
				return jserrorCode.toJSONString();
			} else {
				msgtype = jsStr.get("msgtype").toString();
			}
			// 判断是否是登录 如果不是则验证 token
			if (msgtype.compareTo(REGISTER_CODE) != 0 && msgtype.compareTo(LOGIN_CODE) != 0
					&& msgtype.compareTo(SMS_CODE) != 0 && msgtype.compareTo(RESET_PASS_CODE) != 0
					&& msgtype.compareTo(APP_VERSION_CODE) != 0) {
				String token = request.getHeader("token");
				// 判断是否有需要的值
				if (!StringUtils.isNotBlank(token)) {
					jserrorCode.put("errorCode", 2);
					jserrorCode.put("errorMessage", "没有token");
					jserrorCode.put("data", datajson);
					return jserrorCode.toJSONString();
				} else {
					// 判断user中 token 是否过期
					String userinfoId = jsStr.get("userinfoId").toString();
					UserInfo user = userInfoService.get(userinfoId);
					// 暂定 30天过期
					Date date = new Date();
					Calendar theCa = Calendar.getInstance();
					theCa.setTime(date);
					theCa.add(theCa.DATE, -30);// 最后一个数字30可改，30天的意思
					Date date30 = theCa.getTime();
					if (user == null) {
						// 错误返回信息
						jserrorCode.put("errorCode", 1);
						jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
						jserrorCode.put("data", datajson);

					}
					// 过期30天 提示过期 重新登录
					if (user.getUpdateDate().getTime() < (date30.getTime()) || token.compareTo(user.getRemark()) != 0) {
						jserrorCode.put("errorCode", 2);
						jserrorCode.put("errorMessage", "token过期，请重新登录");
						jserrorCode.put("data", datajson);
						return jserrorCode.toJSONString();
					}
				}

			}

			switch (msgtype) {

			case REGISTER_CODE:
				// 注册方法 10001
				return register(state, request);
			case USER_EDIT_CODE:
				// 修改用户 10002
				return user_edit(state);
			case USER_VIEW_CODE:
				// 获取用户信息 10003
				return user_view(state);
			case LOGIN_CODE:
				// 登录方法 10004
				return login(state);
			case EDIT_PASS_CODE:
				// 修改密码方法 10005
				return edit_pass(state);
			case RESET_PASS_CODE:
				// 重置密码
				return reset_pass(state, request);
			case SMS_CODE:
				// 发送验证码给用户 10007
				return sendSms(state);
			case PASTURE_CODE:
				// 草场信息 10008
				return pasture(state);
			case LIVESTOCK_CODE:
				// 牲畜信息 10009
				return livestock(state);
			case PASTURE_EDIT_CODE:
				// 更新草场信息 10010
				return pasture_edit(state);
			case LIVESTOCK_EDIT_CODE:
				// 更新畜牧信息 10011
				return livestock_edit(state);
			case IMG_EDIT_CODE:
				// 上传图片 10012
				return img_edit(state, request);
			case ANALYSIS_CODE:
				// 草场分析 10013
				return Analysis(state);
			case ANALYSIS_Result_CODE:
				// 草场分析结果 10014
				return analysis_result(state);
			case ANALYSIS_Result_LIST_CODE:
				// 草场分析结果 10015
				return analysis_result_list(state);

			case NATION_CODE:
				// 民族列表 10051
				return nationList(state);
			case LIVESTOCK_TYPE_LIST_CODE:
				// 畜牧类型列表 10052
				return livestockTypeList(state);
			case ADDRESS_LIST_CODE:
				// 地区列表 10053
				return addressList(state);
			case GRASSLIST_CODE:
				// 草原列表 10054
				return grassList(state);
			case UP_CODE:
				// 上传图片 10061
				return upimg(state, request);
			case DISTANCE_CODE:
				// 根据坐标点求面积
				return DistanceList(state);
			case APP_VERSION_CODE:
				// 获取app更新接口
				return appversion(state);
			case HIS_ANALYSIS_CODE:// 根据草场id获取历史草场数据
				// 获取app更新接口
				return getHisAnalsis(state);
			case ANALYSIS_IMAGES:// 根据草场id获取历史草场数据
				// 获取app更新接口
				return getHisAnalsisImages(state);
			case FEEDBACK:
				return feedback_edit(state);// 意见反馈
			default:
				jserrorCode.put("errorCode", 1);
				jserrorCode.put("errorMessage", "未定义方法");
				jserrorCode.put("data", datajson);
				return jserrorCode.toJSONString();
			}

		} catch (Exception e) {
			e.printStackTrace();
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "系统异常");
			jserrorCode.put("data", e.toString());
			return jserrorCode.toJSONString();
		}

	}

	/**
	 * 获取分析图片
	 *
	 */
	public String getHisAnalsisImages(String signature) {
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		GrassImgs grassImgs = new GrassImgs();
		grassImgs.setAnalysisId(jsStr.getString("analysisId"));
		List<GrassImgs> list = grassImgsService.findList(grassImgs);
		// 错误返回信息
		jserrorCode.put("errorCode", 0);
		jserrorCode.put("errorMessage", "成功");
		jserrorCode.put("data", list);
		return JsonMapper.toJsonString(jserrorCode);
	}

	/***
	 * 获取历史草场数据
	 */
	public String getHisAnalsis(String signature) {
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		GrassAnalysis grassAnalysis = new GrassAnalysis();
		UserGrasslandInfo grass = new UserGrasslandInfo();
		grass.setId(jsStr.getString("grassId"));
		grassAnalysis.setGrass(grass);
		List<GrassAnalysis> list = grassAnalysisService.findListSumData(grassAnalysis);
		// 错误返回信息
		jserrorCode.put("errorCode", 0);
		jserrorCode.put("errorMessage", "成功");
		jserrorCode.put("data", list);
		return JsonMapper.toJsonString(jserrorCode);

	}

	/**
	 * 用户注册方法 10001
	 * 
	 * @param signature
	 * @return
	 */
	public String register(String signature, HttpServletRequest request) {
		JSONObject datajson = new JSONObject();

		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();

		// ----------------第一步开始 验证用户是否重复注册
		// 查询用户名是否重复注册
		user.setUsername(jsStr.get("username").toString());
		List<UserInfo> newUserList = userInfoService.findList(user);
		// 重复注册 返回用户名已存在
		if (newUserList.size() > 0) {
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户名已存在，请更换后重新注册");
			jserrorCode.put("data", datajson);
			return jserrorCode.toJSONString();
		}
		// -----------------第一步结束

		// ----------------第二步开始 验证 手机验证码是否正确
		HttpSession session = request.getSession(true);
		String vCode = jsStr.get("code").toString();

		// 数据为1的时候进行验证码验证
		int ret = cvCodeVerification(user.getUsername(), vCode, session, smsInfoService);
		if (ret == 2) {
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "无效验证码");
			jserrorCode.put("data", datajson);
			return jserrorCode.toString();
		} else if (ret == 1) {
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "验证码错误次数超限");
			jserrorCode.put("data", datajson);
			return jserrorCode.toString();
		}
		// ----------------第二步结束

		// -----------------第三部开始 用户数据进行保存
		// 用户类型
		user.setUserType("0");
		// 用户密码 //暂未加密
		user.setPassword(md5encoder.encodePassword(jsStr.get("password").toString(), jsStr.get("username").toString()));
		// user.setPassword(jsStr.get("password").toString());
		// 储存token，每次进行修改用户信息操作 续费 token 。每次登陆更改token
		UUID uuid = UUID.randomUUID();
		user.setRemark(uuid.toString());
		// 用户经纬度
		user.setLat("0");
		user.setLon("0");
		// 保存用户信息
		userInfoService.save(user);

		// 定义data返回数据
		datajson = new JSONObject();
		datajson.put("token", user.getRemark());
		datajson.put("userinfoId", user.getId());
		datajson.put("userType", user.getUserType());

		// -----------------第三部结束 用户数据进行保存

		// 成功返回信息
		jserrorCode.put("errorCode", 0);
		jserrorCode.put("errorMessage", "用户创建成功");
		jserrorCode.put("data", datajson);

		return jserrorCode.toString();
	}

	/**
	 * 修改用户信息 10002
	 * 
	 * @param signature
	 * @return
	 */
	public String user_edit(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册
		user = userInfoService.get(jsStr.getString("userinfoId"));
		// 没有用户 返回用户信息不存在
		if (user == null) {
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息不存在");
			jserrorCode.put("data", datajson);
			return jserrorCode.toJSONString();
		}
		// 修改用户信息
		user.setName(jsStr.getString("name"));
		Area area = new Area();
		area.setId(jsStr.getString("areaId"));
		user.setArea(area);
		user.setAddress(jsStr.getString("address"));
		user.setNationType(jsStr.getString("nationType"));
		user.setHeadImg(jsStr.getString("headImg"));

		// 保存信息
		userInfoService.save(user);

		// 成功返回信息
		jserrorCode.put("errorCode", 0);
		jserrorCode.put("errorMessage", "用户修改成功");
		jserrorCode.put("data", datajson);

		return jserrorCode.toString();
	}

	/**
	 * 获取用户信息 10003
	 * 
	 * @param signature
	 * @return
	 */
	public String user_view(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册
		user = userInfoService.get(jsStr.getString("userinfoId"));
		if (user == null) {
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息不存在");
			jserrorCode.put("data", datajson);
			return jserrorCode.toJSONString();
		}
		// 成功返回信息
		// String mk = JSONObject.toJSONString(user);
		// 定义data返回数据
		datajson = new JSONObject();
		datajson.put("userinfoId", user.getId());
		datajson.put("name", user.getName());
		datajson.put("createDate", user.getCreateDate());
		datajson.put("nationType", user.getNationType());
		datajson.put("userType", user.getUserType());
		datajson.put("username", user.getUsername());
		datajson.put("address", user.getAddress());

		if (StringUtils.isNoneBlank(user.getNationType())) {
			Dict dict = new Dict();
			dict.setType("nation_type");
			List<Dict> list = dictService.findList(dict);
			for (Dict item : list) {
				if (item.getValue().compareTo(user.getNationType()) == 0) {
					datajson.put("nationName", item.getLabel());
				}
			}
		}

		// datajson.put("areaId", user.getArea().getId());
		if (user.getArea() != null) {
			datajson.put("areaId", user.getArea().getId());

			datajson.put("areaName", areaService.get(user.getArea().getId()).getName());
		}
		datajson.put("headImg", user.getHeadImg());

		jserrorCode.put("errorCode", 0);
		jserrorCode.put("errorMessage", "成功");
		jserrorCode.put("data", datajson);
		return jserrorCode.toJSONString();
		// return
		// JSONObject.toJSONString(jserrorCode,SerializerFeature.WriteMapNullValue);
	}

	/**
	 * 用户登录 10004
	 * 
	 * @param signature
	 * @return
	 */
	public String login(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册
		// user=userInfoService.get(jsStr.getString("userinfoId"));
		user.setUsername(jsStr.getString("username"));

		user.setPassword(md5encoder.encodePassword(jsStr.get("password").toString(), jsStr.get("username").toString()));
		// user.setPassword(jsStr.getString("password"));

		user = userInfoService.getLogin(user);
		if (user != null && user.getId().compareTo("") != 0) {
			user.setUpdateDate(DateTime.now().toDate());
			// 储存token，每次进行修改用户信息操作 续费 token 。每次登陆更改token
			UUID uuid = UUID.randomUUID();
			user.setRemark(uuid.toString());
			// 用户经纬度
			if (StringUtils.isNoneBlank(jsStr.get("lat").toString())) {
				user.setLat(jsStr.get("lat").toString());
				user.setLon(jsStr.get("log").toString());
			}
			// 重置用户密码
			user.setPassword(
					md5encoder.encodePassword(jsStr.get("password").toString(), jsStr.get("username").toString()));
			// user.setPassword(jsStr.get("password").toString());
			userInfoService.save(user);

			// 定义data返回数据
			datajson = new JSONObject();
			datajson.put("token", user.getRemark());
			datajson.put("userinfoId", user.getId());
			datajson.put("userType", user.getUserType());

			// 成功返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "用户登录成功");
			jserrorCode.put("data", datajson);
		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户登录失败，请核对账户与密码");
			jserrorCode.put("data", datajson);
		}

		return jserrorCode.toString();
	}

	/**
	 * 修改密码接口10005
	 * 
	 * @param signature
	 * @return
	 */
	public String edit_pass(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册
		user = userInfoService.get(jsStr.getString("userinfoId"));
		// 判断用户是否存在
		if (user != null) {
			user.setUsername(user.getUsername());

			user.setPassword(md5encoder.encodePassword(jsStr.get("oldpassword").toString(), user.getUsername()));
			// user.setPassword(jsStr.getString("oldpassword"));

			UserInfo olduser = userInfoService.getLogin(user);

			if (olduser != null) {

				user.setPassword(md5encoder.encodePassword(jsStr.get("password").toString(), user.getUsername()));
				// user.setPassword(jsStr.getString("password"));
				userInfoService.save(user);
				// 定义data返回数据
				datajson = new JSONObject();
				datajson.put("token", user.getRemark());
				datajson.put("userinfoId", user.getId());

				// 成功返回信息
				jserrorCode.put("errorCode", 0);
				jserrorCode.put("errorMessage", "用户修改密码成功");
				jserrorCode.put("data", datajson);
			} else {
				// 错误返回信息
				jserrorCode.put("errorCode", 1);
				jserrorCode.put("errorMessage", "用户修改失败，请核对账户与密码");
				jserrorCode.put("data", datajson);
			}

		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户修改失败，错误的用户ID");
			jserrorCode.put("data", datajson);
		}

		return jserrorCode.toString();
	}

	/**
	 * 重置密码
	 * 
	 * @param signature
	 * @return
	 */
	public String reset_pass(String signature, HttpServletRequest request) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册
		user.setUsername(jsStr.get("username").toString());
		List<UserInfo> newUserList = userInfoService.findList(user);
		//
		if (newUserList.size() > 0) {
			user = newUserList.get(0);
			// 验证 验证码是否正确
			HttpSession session = request.getSession(true);
			String vCode = jsStr.get("code").toString();

			// 数据为1的时候进行验证码验证
			int ret = cvCodeVerification(user.getUsername(), vCode, session, smsInfoService);
			if (ret == 2) {
				jserrorCode.put("errorCode", 1);
				jserrorCode.put("errorMessage", "无效验证码");
				jserrorCode.put("data", datajson);
				return jserrorCode.toString();
			} else if (ret == 1) {
				jserrorCode.put("errorCode", 1);
				jserrorCode.put("errorMessage", "验证码错误次数超限");
				jserrorCode.put("data", datajson);
				return jserrorCode.toString();
			}

			user.setPassword(md5encoder.encodePassword(jsStr.get("password").toString(), user.getUsername()));
			// user.setPassword(jsStr.getString("password"));
			userInfoService.save(user);
			// 定义data返回数据
			datajson = new JSONObject();
			datajson.put("token", user.getRemark());
			datajson.put("userinfoId", user.getId());

			// 成功返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "用户修改密码成功");
			jserrorCode.put("data", datajson);

		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户修改失败，错误的用户ID");
			jserrorCode.put("data", datajson);
		}

		return jserrorCode.toString();

	}

	/**
	 * 发送验证码 10007
	 * 
	 * @param signature
	 * @return
	 */
	public String sendSms(String signature) {
		JSONObject datajson = new JSONObject();

		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);

		SmsInfo smsInfo = new SmsInfo();
		smsInfo.setMobile(jsStr.getString("username"));
		int ret = SmsUtils.SmsSend(smsInfo);
		if (ret == 0) {
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("data", datajson);
			jserrorCode.put("errorMessage", "发送成功");
		} else {
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("data", datajson);
			jserrorCode.put("errorMessage", "发送失败");
		}
		return jserrorCode.toString();
	}

	/**
	 * 草场信息 10008
	 * 
	 * @param signature
	 * @return
	 */
	public String pasture(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));
		UserGrasslandInfo usergrasslandinfo = new UserGrasslandInfo();
		if (user != null) {
			usergrasslandinfo.setUserinfo(user);
			Page<UserGrasslandInfo> list = userGrasslandInfoService.findPage(new Page<UserGrasslandInfo>(1, 99),
					usergrasslandinfo);

			// 定义data返回数据
			JSONArray jsonArray = new JSONArray();
			for (UserGrasslandInfo item : list.getList()) {
				datajson = new JSONObject();
				datajson.put("id", item.getId());
				datajson.put("name", item.getName());
				datajson.put("area", item.getArea());
				datajson.put("clArea", item.getClArea());
				datajson.put("grassImg", item.getGrassImg());
				datajson.put("coordinates", item.getCoordinates());
				datajson.put("address", user.getAddress());
				datajson.put("create", item.getCreateDate());
				// 判断是否有草场分析信息
				GrassAnalysis grassAnalysis = new GrassAnalysis();
				grassAnalysis.setGrass(item);
				// 获取
				GrassAnalysis grassAnalysislist = grassAnalysisService.getResult(grassAnalysis);
				if (grassAnalysislist != null) {
					datajson.put("IsAnalysis", 1);
					grassAnalysis = grassAnalysislist;
					datajson.put("avgVal", grassAnalysis.getAvgVal());

					/*
					 * List<GrassImgs> IMGlist = new ArrayList<GrassImgs>();
					 * 
					 * GrassImgs grassImgs =new GrassImgs();
					 * grassImgs.setAnalysisId(grassAnalysis.getId());
					 * IMGlist=grassImgsService.findList(grassImgs);
					 * 
					 * Map<String, Object> map = Maps.newHashMap(); List<Map<String, Object>> zmap =
					 * Lists.newArrayList(); for (GrassImgs grassImgsitem : IMGlist) { map =
					 * Maps.newHashMap(); map.put("val", grassImgsitem.getAnalysisVal());
					 * map.put("url", grassImgsitem.getImgPath()); zmap.add(map); } //分析过的图片
					 * datajson.put("imglist", JSONObject.toJSON(zmap));
					 */

				} else {
					datajson.put("IsAnalysis", 0);
					datajson.put("avgVal", 0);
				}

				jsonArray.add(datajson);

			}

			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("pageNo", list.getPageNo());
			jserrorCode.put("pageSize", list.getPageSize());
			jserrorCode.put("totalPages", list.getTotalPage());
			jserrorCode.put("errorMessage", "查询成功");
			jserrorCode.put("data", jsonArray);
		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 牲畜信息 10009
	 * 
	 * @param signature
	 * @return
	 */
	public String livestock(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));
		UserLivestockInfo userLivestockInfo = new UserLivestockInfo();
		if (user != null) {

			userLivestockInfo.setUserinfo(user);
			// Page<UserLivestockInfo> page = userLivestockInfoService.findPage(new
			// Page<UserLivestockInfo>(0, 100), userLivestockInfo);
			// 2018-10-22 新增加三行 草场id 草场信息
			UserGrasslandInfo grasslandInfo = new UserGrasslandInfo();
			grasslandInfo.setId(jsStr.getString("grasslandInfoId"));
			userLivestockInfo.setUserGrasslandInfo(grasslandInfo);

			// 定义data返回数据
			JSONArray jsonArray = new JSONArray();
			List<UserLivestockInfo> liststock = userLivestockInfoService.findptList(userLivestockInfo);
			List<Dict> stocklist = DictUtils.getDictList("livestock_type");

			for (UserLivestockInfo item : liststock) {
				datajson = new JSONObject();
				datajson.put("id", item.getId());
				datajson.put("livestockType", item.getLivestockType());
				Dict olddict = new Dict();
				olddict.setType(item.getLivestockType());
				for (Dict dict : stocklist) {
					if (dict.getValue().compareTo(item.getLivestockType()) == 0) {
						datajson.put("livestockTypeName", dict.getLabel());
					}
				}
				// 2018-10-22 新增加一行 草场id
				datajson.put("grasslandInfoId", item.getuserGrasslandInfo().getId());
				datajson.put("address", user.getAddress());
				datajson.put("count", item.getCount());
				datajson.put("create", item.getCreateDate());
				datajson.put("img", item.getImg());
				jsonArray.add(datajson);

			}
			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			// jserrorCode.put("pageNo", page.getPageNo());
			// jserrorCode.put("pageSize", page.getPageSize());
			// jserrorCode.put("totalPages", page.getTotalPage());
			jserrorCode.put("errorMessage", "查询成功");
			jserrorCode.put("data", jsonArray);
		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 更新草场信息 10010
	 * 
	 * @param signature
	 * @return
	 */
	public String pasture_edit(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));
		UserGrasslandInfo usergrasslandinfo = new UserGrasslandInfo();
		if (user != null) {
			String id = jsStr.getString("id");
			if (StringUtils.isNotBlank(id)) {
				// 判断删除标志是否为空 不为空进行删除
				String del = jsStr.getString("del");
				if (StringUtils.isNotBlank(del)) {

					usergrasslandinfo = userGrasslandInfoService.get(id);
					userGrasslandInfoService.delete(usergrasslandinfo);
					// 返回信息
					jserrorCode.put("errorCode", 0);
					jserrorCode.put("errorMessage", "删除成功");
					jserrorCode.put("data", datajson);
					return jserrorCode.toString();
				}
				usergrasslandinfo = userGrasslandInfoService.get(id);
				usergrasslandinfo.setUserinfo(user);
				String area = "0";
				String clArea = "0";
				if (!StringUtils.isBlank(jsStr.getString("area")))
					area = jsStr.getString("area");
				if (!StringUtils.isBlank(jsStr.getString("clArea")))
					clArea = jsStr.getString("clArea");
				usergrasslandinfo.setArea(area);
				usergrasslandinfo.setClArea(clArea);
				usergrasslandinfo.setCoordinates(jsStr.getString("coordinates"));
				List<Coordinates> ts = (List<Coordinates>) JSONArray.parseArray(jsStr.getString("coordinates"),
						Coordinates.class);
				for (int i = 0; i < ts.size(); i++) {
					Coordinates coor = ts.get(i);
					if (coor.getSort().compareTo("1") == 0) {
						usergrasslandinfo.setLat(coor.getLat());
						usergrasslandinfo.setLon(coor.getLon());
					}
				}
				usergrasslandinfo.setGrassImg(jsStr.getString("grassImg"));
				usergrasslandinfo.setName(jsStr.getString("name"));
			} else {
				usergrasslandinfo.setUserinfo(user);
				usergrasslandinfo.setArea(jsStr.getString("area"));
				usergrasslandinfo.setClArea(jsStr.getString("clArea"));
				List<Coordinates> ts = (List<Coordinates>) JSONArray.parseArray(jsStr.getString("coordinates"),
						Coordinates.class);
				for (int i = 0; i < ts.size(); i++) {
					Coordinates coor = ts.get(i);
					if (coor.getSort().compareTo("1") == 0) {
						usergrasslandinfo.setLat(coor.getLat());
						usergrasslandinfo.setLon(coor.getLon());
					}
				}
				usergrasslandinfo.setCoordinates(jsStr.getString("coordinates"));
				usergrasslandinfo.setGrassImg(jsStr.getString("grassImg"));
				usergrasslandinfo.setName(jsStr.getString("name"));

			}
			userGrasslandInfoService.save(usergrasslandinfo);
			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "修改成功");
			jserrorCode.put("data", datajson);
		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 畜牧维护信息 10011
	 * 
	 * @param signature
	 * @return
	 */
	public String livestock_edit(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));
		UserLivestockInfo userLivestockInfo = new UserLivestockInfo();
		if (user != null) {

			String id = jsStr.getString("id");

			// 2018-10-22 新增草场信息
			UserGrasslandInfo grasslandInfo = new UserGrasslandInfo();
			grasslandInfo.setId(jsStr.getString("grasslandInfoId"));

			if (StringUtils.isNotBlank(id)) {
				// 判断删除标志是否为空 不为空进行删除
				String del = jsStr.getString("del");
				if (StringUtils.isNotBlank(del)) {

					userLivestockInfo.setId(id);
					userLivestockInfoService.delete(userLivestockInfo);
					// 返回信息
					jserrorCode.put("errorCode", 0);
					jserrorCode.put("errorMessage", "删除成功");
					jserrorCode.put("data", datajson);
					return jserrorCode.toString();
				}

				userLivestockInfo.setId(id);
				userLivestockInfo.setUserinfo(user);
				userLivestockInfo.setLivestockType(jsStr.getString("livestockType"));
				// userLivestockInfo(jsStr.getString("livestockTypeName"));
				userLivestockInfo.setCount(jsStr.getString("count"));
				userLivestockInfo.setImg(jsStr.getString("img"));
				// 2018-10-22 新增草场信息
				userLivestockInfo.setUserGrasslandInfo(grasslandInfo);

				userLivestockInfoService.save(userLivestockInfo);
				// 错误返回信息
				jserrorCode.put("errorCode", 0);
				jserrorCode.put("errorMessage", "修改成功");
				jserrorCode.put("data", datajson);
			} else {

				userLivestockInfo.setUserinfo(user);
				userLivestockInfo.setLivestockType(jsStr.getString("livestockType"));
				// userLivestockInfo(jsStr.getString("livestockTypeName"));
				userLivestockInfo.setCount(jsStr.getString("count"));
				userLivestockInfo.setImg(jsStr.getString("img"));
				// 2018-10-22 新增草场信息
				userLivestockInfo.setUserGrasslandInfo(grasslandInfo);

				// 判断此牲畜是否已经添加
				List<UserLivestockInfo> list = userLivestockInfoService.findList(userLivestockInfo);
				if (list.size() > 0) {
					// 错误返回信息
					jserrorCode.put("errorCode", 1);
					jserrorCode.put("errorMessage", "牲畜类型已添加");
				} else {
					userLivestockInfoService.save(userLivestockInfo);
					// 错误返回信息
					jserrorCode.put("errorCode", 0);
					jserrorCode.put("errorMessage", "添加成功");
					jserrorCode.put("data", datajson);
				}

			}

		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 上传图片 返回图片中绿色百分比 10012
	 * 
	 * @param signature
	 * @return
	 * @throws IOException
	 */
	public String img_edit(String signature, HttpServletRequest request) throws IOException {
		JSONObject datajson = new JSONObject();

		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));

		if (user != null) {
			// 工具类
			UploadUtils file = new UploadUtils();
			String imgPath = jsStr.getString("imgPath");
			String val = ImageHeler.analyseRGB(imgPath);
			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "上传成功");
			jserrorCode.put("data", val);
		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 草量分析 10013
	 * 
	 * @param signature
	 * @return
	 */
	public String Analysis(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		int year = DateTime.now().getYear();
		int month = DateTime.now().getMonthOfYear();
		user = userInfoService.get(jsStr.getString("userinfoId"));
		GrassAnalysis grass = new GrassAnalysis();
		UserGrasslandInfo usergrass = new UserGrasslandInfo();
		double userArea = 0;
		// 查询用户名是否注册
		if (user != null) {
			// 草场信息
			grass.setAvgVal(jsStr.getString("avgVal"));
			// 草原标准值

			usergrass = userGrasslandInfoService.get(jsStr.getString("grassId"));
			// 用户草场亩
			userArea = Double.parseDouble(usergrass.getArea());
			grass.setGrass(usergrass);
			// 经纬度
			grass.setLon(jsStr.getString("lon"));
			grass.setLat(jsStr.getString("lat"));
			// 年月
			grass.setMonth(String.valueOf(DateTime.now().getMonthOfYear()));
			grass.setYear(String.valueOf(DateTime.now().getYear()));

			// 搜索距离最近的一个草原带中的标准点
			SysGrassBelt sysGrassBelt = new SysGrassBelt();
			// 新增判断如果拍照位置与草场位置相差太远(50公里以内)，那么以草场位置作为拍照位置
			if (StringUtils.isNotBlank(usergrass.getLat()) && StringUtils.isNotBlank(usergrass.getLon())) {
				double distance = MapAreaUtils.GetDistance(Double.parseDouble(grass.getLat()),
						Double.parseDouble(grass.getLon()), Double.parseDouble(usergrass.getLat()),
						Double.parseDouble(usergrass.getLon())) / 1000;
				if (distance > 100) // 100公里距离
				{
					sysGrassBelt.setLat(usergrass.getLat());
					sysGrassBelt.setLon(usergrass.getLon());
				}
			} else {
				sysGrassBelt.setLat(grass.getLat());
				sysGrassBelt.setLon(grass.getLon());
			}

			sysGrassBelt = sysGrassBeltService.getNearby(sysGrassBelt);

			grass.setGrassBelt(sysGrassBelt);

			// 获取用户畜牧
			// 2018-10-22 更改获取牲畜的方式，通过传递过来的草场ID 获取对应的牲畜信息
			// List<UserLivestockInfo> stockList = user.getStockList();//更改前代码

			UserLivestockInfo userLivestockInfo = new UserLivestockInfo();
			userLivestockInfo.setUserinfo(user);
			userLivestockInfo.setUserGrasslandInfo(usergrass);
			List<UserLivestockInfo> stockList = userLivestockInfoService.findptList(userLivestockInfo);
			// 2018-10-22 更改结束

			// 数量

			Dict dict = new Dict();
			dict.setType("livestock_type");
			List<Dict> dictlist = dictService.findList(dict);

			String[][] arrtype = new String[stockList.size()][2];
			for (int i = 0; i <stockList.size(); i++) {

				for (Dict item : dictlist) { 
					if (item.getValue().compareTo(stockList.get(i).getLivestockType().toString()) == 0) {
						String[] arr = stockList.get(i).getLivestockType().split("-");
						// 类型名字
						arrtype[i][0] = item.getLabel();
						// 类型量
						arrtype[i][1] = arr[1];
					}
				}
			}

			// app输入的公斤/亩产量
			double sjchanliang = 0, chanliang = 0;
			GrassType grassType = grassTypeService.get(sysGrassBelt.getGrasstype().getId());
			double beltMonthxishu = getXishu(sysGrassBelt.getMonth(), grassType);
			double curMonthxishu = getXishu(month + "", grassType);
			// 根据草原带计算草地参量
			chanliang = grassCoverageService.getNearGrass(sysGrassBelt, grass.getAvgVal(), beltMonthxishu,
					curMonthxishu);
			sjchanliang = chanliang;
			// 如果app输入标准值公斤/亩 直接保存
			if (StringUtils.isNoneBlank(jsStr.getString("stand8val"))) {
				chanliang = Double.parseDouble(jsStr.getString("stand8val"));
			}

			/*
			 * if(xishu == 0) { //错误返回信息 jserrorCode.put("errorCode", 1);
			 * jserrorCode.put("errorMessage", "当月没有草量"); jserrorCode.put("data", datajson);
			 * }
			 */

			//
			double nowcarryingGrass = chanliang;// ((biaozhuncl8*xishu)/biaozhunzhi8) *
												// Double.parseDouble(grass.getAvgVal());
			// 标准值
			grass.setStandVal(sjchanliang + "");
			grass.setNowStandVal(chanliang + "");
			// 草量
			double sumnowcarryingGrass = userArea * nowcarryingGrass;
			grass.setNowCarryingGrass(sumnowcarryingGrass + "");
			// 默认当月洗漱计算出的草量 //
			double carryingGrass = sjchanliang;
			double sumCarryingGrass = userArea * carryingGrass;
			grass.setCarryingGrass(sumCarryingGrass + "");
			// 载畜量
			String CarryingLivestock = "";
			String NowCarryingLivestock = "";
			if (arrtype.length != 0) {
				// 2018-10-22 更改

				// for (String[] strings : arrtype) {
				// CarryingLivestock+= strings[0]+":" +
				// Math.floor(sumCarryingGrass/Double.parseDouble(strings[1])) +",";
				// NowCarryingLivestock+=strings[0]+":" +
				// Math.floor(sumnowcarryingGrass/Double.parseDouble(strings[1]))+",";
				// } //2018-10-22 更改前代码
				// 总消耗量
				double xhl = 0;
				for (String[] strings : arrtype) {
					CarryingLivestock += strings[0] + "、";
					NowCarryingLivestock += strings[0] + "、";
					xhl += Double.parseDouble(strings[1]);
				}
				CarryingLivestock += "共吃"+Math.floor(sumCarryingGrass / xhl)+"天";
				NowCarryingLivestock += "共吃"+Math.floor(sumnowcarryingGrass / xhl)+"天";
				// 2018-10-22 更改结束
			} else {
				CarryingLivestock += "100只羊:" + Math.floor(sumCarryingGrass / 2 * 100);
				NowCarryingLivestock += "100只羊:" + Math.floor(sumCarryingGrass / 2 * 100);
			}

			grass.setCarryingLivestock(CarryingLivestock);
			grass.setNowCarryingLivestock(NowCarryingLivestock);
			grass.setUserinfo(user);
			// 存储 图片
			// grass.setRemark(jsStr.getString("remark"));
			JSONArray array = jsStr.getJSONArray("remark");
			// 保存分析结果
			grassAnalysisService.save(grass);

			// 草场分析结果
			GrassAnalysis grassAnalysis = new GrassAnalysis();
			// 获取草场分析结果
			usergrass.setId(jsStr.getString("grassId"));
			grassAnalysis.setGrass(usergrass);
			grassAnalysis.setMonth(String.valueOf(year));
			grassAnalysis.setYear(String.valueOf(month));
			// 获取草场分析结果
			grassAnalysis = grassAnalysisService.getResult(grassAnalysis);
			// 保存分析图片
			GrassImgs grassImgs = new GrassImgs();
			// 判断是否做过分析
			if (grassAnalysis != null) {
				grassImgs.setAnalysisId(grassAnalysis.getId());
				// 删除 所有分析图片
				grassImgsService.deleteList(grassImgs);
			}

			// 生成所有分析图片 并存放值
			if (array.size() > 0) {
				for (int i = 0; i < array.size(); i++) {
					grassImgs = new GrassImgs();
					// 遍历 jsonarray 数组，把每一个对象转成 json 对象
					JSONObject job = array.getJSONObject(i);
					// 得到 每个对象中的属性值
					// 设置分析ID
					grassImgs.setAnalysisId(grass.getId());
					// 设置草场ID
					grassImgs.setGrassId(grass.getGrass().getId());
					// 设置图片地址
					grassImgs.setImgPath(job.getString("url"));
					// 设置图片分析值
					if (StringUtils.isNoneBlank(job.getString("val")))
						grassImgs.setAnalysisVal(job.getString("val"));
					else
						grassImgs.setAnalysisVal("0");

					grassImgs.setDelFlag("0");

					grassImgsService.save(grassImgs);

				}
			}

			datajson.put("year", year);
			datajson.put("month", month);
			// 返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "上传成功");
			jserrorCode.put("data", datajson);

		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();

	}

	/**
	 * 草场分析结果10014
	 * 
	 * @param signature
	 * @return
	 */
	public String analysis_result(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册
		user = userInfoService.get(jsStr.getString("userinfoId"));

		if (user != null) {
			List<GrassImgs> list = new ArrayList<GrassImgs>();

			GrassImgs grassImgs = new GrassImgs();
			grassImgs.setAnalysisId(jsStr.getString("analysisId"));
			list = grassImgsService.findList(grassImgs);

			Map<String, Object> map = Maps.newHashMap();
			Map<String, Object> zmap = Maps.newHashMap();
			for (GrassImgs grassImgsitem : list) {
				map = Maps.newHashMap();
				map.put("val", grassImgsitem.getAnalysisVal());
				map.put("img", grassImgsitem.getImgPath());
				zmap.put("list", map);
			}

			// 返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", zmap);

		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 返回分析结果列表10015
	 * 
	 * @param signature
	 * @return
	 */
	public String analysis_result_list(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册
		user = userInfoService.get(jsStr.getString("userinfoId"));
		JSONArray jsonArray = new JSONArray();
		if (user != null) {
			// 草场信息
			UserGrasslandInfo usergrass = new UserGrasslandInfo();
			// 分析结果
			GrassAnalysis grassAnalysis = new GrassAnalysis();
			// 根据ID获取草场信息
			usergrass.setUserinfo(user);
			List<UserGrasslandInfo> list = userGrasslandInfoService.findList(usergrass);
			// 循环获得草场信息
			for (UserGrasslandInfo itemug : list) {
				grassAnalysis.setGrass(itemug);

				// 根据草场 获取 分析结果
				GrassAnalysis item = grassAnalysisService.getResult(grassAnalysis);

				// for(GrassAnalysis item:grassAnalysislist)
				// {
				if (item != null) {
					datajson = new JSONObject();

					datajson.put("id", item.getId());
					datajson.put("year", item.getYear());
					datajson.put("month", item.getMonth());
					// 2018-1-23 添加一条修改时间
					datajson.put("updateDate", item.getCreateDate());
					// 标准值
					datajson.put("standval", item.getNowStandVal());
					// 草量
					datajson.put("carryingGrass", item.getNowCarryingGrass());
					// 载畜量
					datajson.put("carryingLivestock", item.getNowCarryingLivestock());

					// 草场图片
					datajson.put("grassImg", itemug.getGrassImg());
					// 草场名称
					datajson.put("grassName", itemug.getName());
					// 草场地址
					datajson.put("address", user.getAddress());
					// 草场id
					datajson.put("grassId", itemug.getId());
					// 亩数
					datajson.put("grassArea", itemug.getArea());

					List<GrassImgs> IMGlist = new ArrayList<GrassImgs>();

					GrassImgs grassImgs = new GrassImgs();
					grassImgs.setAnalysisId(item.getId());
					IMGlist = grassImgsService.findList(grassImgs);

					Map<String, Object> map = Maps.newHashMap();
					List<Map<String, Object>> zmap = Lists.newArrayList();
					for (GrassImgs grassImgsitem : IMGlist) {
						map = Maps.newHashMap();
						map.put("val", grassImgsitem.getAnalysisVal());
						map.put("url", grassImgsitem.getImgPath());
						zmap.add(map);
					}
					// 分析过的图片
					datajson.put("imglist", JSONObject.toJSON(zmap));
					jsonArray.add(datajson);
				}

				// }
			}
			// 返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", jsonArray);

		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 图片上传 返回地址
	 * 
	 * @param signature
	 * @param request
	 * @param head_url
	 * @return
	 */
	public String upimg(String signature, HttpServletRequest request) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		if (user != null) {
			UploadUtils file = new UploadUtils();

			// 判断 是否进行上传图片
			String up[] = file.uploadFile(request);

			if (up[0].equals("true")) {
				datajson.put("url", up[4]);
				// 返回信息
				jserrorCode.put("errorCode", 0);
				jserrorCode.put("errorMessage", "成功");
				jserrorCode.put("data", datajson);
			}

		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 畜牧类型列表
	 * 
	 * @param signature
	 * @return
	 */
	public String livestockTypeList(String signature) {

		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));

		if (user != null) {
			List<Map<String, Object>> mapList = Lists.newArrayList();
			Dict dict = new Dict();
			dict.setType("livestock_type");
			List<Dict> list = dictService.findList(dict);
			for (int i = 0; i < list.size(); i++) {
				Dict e = list.get(i);
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getValue());
				map.put("pId", e.getParentId());
				map.put("name", StringUtils.replace(e.getLabel(), " ", ""));
				mapList.add(map);
			}

			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", JSONObject.toJSON(mapList));
		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 地址列表
	 * 
	 * @param signature
	 * @return
	 */
	public String addressList(String signature) {

		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));
		String pid = jsStr.getString("pid");

		if (user != null) {
			List<Map<String, Object>> mapList = Lists.newArrayList();
			List<Area> list = areaService.findAll();
			for (int i = 0; i < list.size(); i++) {
				Area e = list.get(i);
				if (e.getParentId().compareTo(pid) == 0) {
					Map<String, Object> map = Maps.newHashMap();
					map.put("id", e.getId());
					map.put("pId", e.getParentId());
					map.put("name", e.getName());
					mapList.add(map);
				}
			}

			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", JSONObject.toJSON(mapList));
		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 民族列表
	 * 
	 * @param signature
	 * @return
	 */
	public String nationList(String signature) {
		JSONObject datajson = new JSONObject();

		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));

		if (user != null) {

			List<Map<String, Object>> mapList = Lists.newArrayList();
			Dict dict = new Dict();
			dict.setType("nation_type");
			List<Dict> list = dictService.findList(dict);
			for (int i = 0; i < list.size(); i++) {
				Dict e = list.get(i);
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getValue());
				map.put("pId", e.getParentId());
				map.put("name", StringUtils.replace(e.getLabel(), " ", ""));
				mapList.add(map);
			}
			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", JSONObject.toJSON(mapList));
		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 草原列表
	 * 
	 * @param signature
	 * @return
	 */
	public String grassList(String signature) {
		JSONObject datajson = new JSONObject();

		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));

		if (user != null) {

			List<Map<String, Object>> mapList = Lists.newArrayList();
			SysGrassBelt sysGrassBelt = new SysGrassBelt();
			List<SysGrassBelt> list = sysGrassBeltService.findList(sysGrassBelt);
			for (SysGrassBelt item : list) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", item.getId());
				map.put("vale", item.getStand8val());
				map.put("name", StringUtils.replace(item.getName(), " ", ""));
				mapList.add(map);
			}

			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", JSONObject.toJSON(mapList));
		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * 计算地址面积
	 * 
	 * @param signature
	 * @return
	 */
	public String DistanceList(String signature) {
		JSONObject datajson = new JSONObject();

		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));

		String jsonString = jsStr.getString("array");

		if (user != null) {

			List<loction> param = JSONArray.parseArray(jsonString, loction.class);

			List<double[]> latLngsList = new ArrayList<double[]>();

			double[] arr = new double[2];

			for (loction item : param) {
				arr = new double[2];
				arr[0] = Double.valueOf(item.lat);
				arr[1] = Double.valueOf(item.lon);
				latLngsList.add(arr);

			}
			if (latLngsList.size() > 0) {
				latLngsList.add(latLngsList.get(0));
			}

			double zongzhouchang = getDistance(latLngsList);
			double r = zongzhouchang / 2 / Math.PI;
			double mianji = r * r * Math.PI;
			datajson.put("s", String.format("%.2f", mianji * 1500));
			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", datajson);
		} else {

			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	/**
	 * app 更新接口
	 * 
	 * @param signature
	 * @return
	 */
	public String appversion(String signature) {
		JSONObject datajson = new JSONObject();

		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		SysAppVersion sysAppVersion = new SysAppVersion();

		sysAppVersion.setPlat(jsStr.getString("plat"));
		sysAppVersion.setIsNew("1");
		List<SysAppVersion> list = sysAppVersionService.findList(sysAppVersion);
		if (list.size() > 0) {
			datajson.put("versionName", list.get(0).getVersionName());
			datajson.put("versionCode", list.get(0).getVersionCode());
			datajson.put("downloadUrl", list.get(0).getDownloadUrl());
			datajson.put("update", list.get(0).getUpdateLog());

			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "成功");
			jserrorCode.put("data", datajson);

		} else {

			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "暂无内容");
			jserrorCode.put("data", datajson);
		}

		return jserrorCode.toString();
	}

	public double getDistance(List<double[]> latLngs) {
		double distance = 0.0;
		if (latLngs.size() >= 2) {
			for (int i = 1; i < latLngs.size(); i++) {
				double R = 6378.137; // 地球半径
				double lat1 = latLngs.get(i - 1)[1] * Math.PI / 180.0;
				double lng1 = latLngs.get(i - 1)[0] * Math.PI / 180.0;
				double lat2 = latLngs.get(i)[1] * Math.PI / 180.0;
				double lng2 = latLngs.get(i)[0] * Math.PI / 180.0;

				double d = Math.acos(
						Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lng2 - lng1)) * R;
				d = (double) Math.round(d * 100000) / 100000;
				distance += d;
			}
		}
		logger.info("distance->{}", distance);
		distance = (double) Math.round(distance * 100000) / 100000;
		return distance;
	}

	/**
	 * 返回数据分析结果网页 web
	 * 
	 * @param grassId
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "result")
	public String result(String json, Model model) {

		String state = StringEscapeUtils.unescapeHtml4(json);
		// 初始化返回参数
		// jserrorCode = new JSONObject();

		// 解析传递过来的json
		JSONObject jsStr = JSONObject.parseObject(state); // 将字符串{“id”：1}

		// 草场信息
		UserGrasslandInfo usergrass = new UserGrasslandInfo();
		// 草场分析结果
		GrassAnalysis grassAnalysis = new GrassAnalysis();
		// 获取草场分析结果
		usergrass.setId(jsStr.getString("grassId"));
		// usergrass.setId("7e3e0226e73c428187594f4991935eea");
		grassAnalysis.setGrass(usergrass);
		grassAnalysis.setYear(jsStr.getString("year"));
		grassAnalysis.setMonth(jsStr.getString("month"));
		// grassAnalysis.setYear("2018");
		// grassAnalysis.setMonth("5");
		// 获取草场分析结果
		grassAnalysis = grassAnalysisService.getResult(grassAnalysis);

		Map<String, Object> map = Maps.newHashMap();

		map.put("id", grassAnalysis.getId());
		map.put("year", grassAnalysis.getYear());
		map.put("month", grassAnalysis.getMonth());
		// 当前载畜量
		map.put("NowcarryingLivestock", grassAnalysis.getNowCarryingLivestock());
		// 当前草量
		map.put("NowcarryingGrass", grassAnalysis.getNowCarryingGrass());
		// 牲畜量
		UserLivestockInfo userLivestockInfo = new UserLivestockInfo();
		UserInfo userinfo = new UserInfo();
		userinfo.setId(jsStr.getString("userinfoId"));
		userLivestockInfo.setUserinfo(userinfo);
		// 添加草场信息
		userLivestockInfo.setUserGrasslandInfo(usergrass);

		List<UserLivestockInfo> livelist = userLivestockInfoService.findptList(userLivestockInfo);
		List<Dict> dictlist = DictUtils.getDictList("livestock_type");
		String nowlivestock = "";
		// 如果有牲畜
		// if (livelist.size() != 0) {
		//
		// for (int i = 0; i < livelist.size(); i++) {
		// for (int z = 0; z < dictlist.size(); z++) {
		// if (livelist.get(i).getLivestockType().compareTo(dictlist.get(z).getValue())
		// == 0) {
		//
		// double oneMore =
		// Double.parseDouble(dictlist.get(z).getValue().split("-")[1]);
		// Double day =
		// Math.floor(Double.parseDouble(grassAnalysis.getNowCarryingGrass())
		// / (oneMore * Integer.parseInt(livelist.get(i).getCount())));
		//
		// nowlivestock += livelist.get(i).getCount() + "只" + dictlist.get(z).getLabel()
		// + "吃"
		// + day.intValue() + "天或";
		//
		// }
		// }
		// }
		//
		// } else {
		// Double day =
		// Math.floor(Double.parseDouble(grassAnalysis.getNowCarryingGrass()) / (2 *
		// 100));
		// nowlivestock += "100只羊吃" + day + "天";
		// }
		//2018-10-27更改前
		//2018-10-27更改后
		if (livelist.size() != 0) { 
			//计算吃草量
			double ccl=0;
			for (int i = 0; i < livelist.size(); i++) {
				for (int z = 0; z < dictlist.size(); z++) {
					if (livelist.get(i).getLivestockType().compareTo(dictlist.get(z).getValue()) == 0) {

						double oneMore = Double.parseDouble(dictlist.get(z).getValue().split("-")[1]);
						
						ccl+=(oneMore * Integer.parseInt(livelist.get(i).getCount()));
						nowlivestock += livelist.get(i).getCount() + "只" + dictlist.get(z).getLabel() ;
							
					}
				
				}	 
			}
			Double day = Math.floor(Double.parseDouble(grassAnalysis.getNowCarryingGrass()) / ccl);
			nowlivestock+="共吃"+day+"天";

		} else {
			Double day = Math.floor(Double.parseDouble(grassAnalysis.getNowCarryingGrass()) / (2 * 100));
			nowlivestock += "100只羊吃" + day + "天";
		}
		 
		// 2018-10-27更改结束

		//nowlivestock = nowlivestock.toString().substring(0, nowlivestock.length() - 1);

		map.put("NowLivestock", nowlivestock);
		// 当月标准值
		map.put("standval", grassAnalysis.getStandVal());
		// 根据当月产量预测下几个月的产量
		SysGrassBelt sysgrassbelt = new SysGrassBelt();
		sysgrassbelt = sysGrassBeltService.get(grassAnalysis.getGrassBelt().getId());
		GrassType grassType = grassTypeService.get(sysgrassbelt.getGrasstype().getId());
		grassAnalysis.setYear(jsStr.getString("year"));

		List<GrassAnalysis> list = grassAnalysisService.findListSumData(grassAnalysis);

		String yue5 = "0";
		String yue6 = "0";
		String yue7 = "0";
		String yue8 = "0";
		String yue9 = "0";
		String yue10 = "0";

		for (int i = 0; i < list.size(); i++) {
			GrassAnalysis gran = list.get(i);
			if (gran.getMonth().compareTo("5") == 0)
				yue5 = gran.getNowStandVal();
			if (gran.getMonth().compareTo("6") == 0)
				yue6 = gran.getNowStandVal();
			if (gran.getMonth().compareTo("7") == 0)
				yue7 = gran.getNowStandVal();
			if (gran.getMonth().compareTo("8") == 0)
				yue8 = gran.getNowStandVal();
			if (gran.getMonth().compareTo("9") == 0)
				yue9 = gran.getNowStandVal();
			if (gran.getMonth().compareTo("10") == 0)
				yue10 = gran.getNowStandVal();
		}

		String[] xitongyuef = { yue5, yue6, yue7, yue8, yue9, yue10 };
		String curchaliang = "0";
		int index = 0;
		for (int i = 0; i < xitongyuef.length; i++) {
			if (xitongyuef[i].compareTo("0") != 0) {
				curchaliang = xitongyuef[i];
				index = i;
			}
			if (curchaliang.compareTo("0") != 0 && xitongyuef[i].compareTo("0") == 0) {
				xitongyuef[i] = getCurMonthXishu(curchaliang, (index + 5) + "", (i + 5) + "", grassType);
			}

		}
		String xitongyuef1 = "[" + xitongyuef[0].toString() + "," + xitongyuef[1].toString() + ","
				+ xitongyuef[2].toString() + "," + xitongyuef[3].toString() + "," + xitongyuef[4].toString() + ","
				+ xitongyuef[5].toString() + "]";
		model.addAttribute("cl", xitongyuef1);
		model.addAttribute("map", map);
		if(Integer.valueOf(grassAnalysis.getAvgVal()) >20)
		{
			return "modules/app/result";
		}
		else 
		{
			
			return "modules/app/resultNo";
		}
		 

	}

	/***
	 * 根据当月系数计算产量
	 */
	public String getCurMonthXishu(String chanliang, String chanliangMonth, String month, GrassType grassType) {
		double xishu = 1;
		double chanliangxishu = 1;
		chanliangxishu = getXishu(chanliangMonth, grassType);
		xishu = getXishu(month, grassType);
		chanliang = Math.floor((Double.parseDouble(chanliang) / chanliangxishu * xishu)) + "";
		return chanliang;
	}

	public double getXishu(String month, GrassType grassType) {
		double xishu = 1;
		switch (month) {
		case "5":
			// 系数
			xishu = Double.parseDouble(grassType.getRatio5());
			break;
		case "6":
			// 系数
			xishu = Double.parseDouble(grassType.getRatio6());
			break;
		case "7":
			// 系数
			xishu = Double.parseDouble(grassType.getRatio7());
			break;
		case "8":
			// 系数
			xishu = Double.parseDouble(grassType.getRatio8());
			break;
		case "9":
			// 系数
			xishu = Double.parseDouble(grassType.getRatio9());
			break;
		case "10":
			// 系数
			xishu = Double.parseDouble(grassType.getRatio10());
			break;

		}
		return xishu;
	}

	/**
	 * 上传图片
	 * 
	 * @param userinfoId
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImage(@RequestParam("userinfoId") String userinfoId, HttpServletRequest request,
			@RequestParam("file") MultipartFile file) {
		String errorMessage = "";
		int errorCode = 0;

		jserrorCode = new JSONObject();
		JSONObject data = new JSONObject();
		if (!StringUtils.isNoneBlank(userinfoId)) {
			errorCode = 1;
			errorMessage = "没有用户ID";
		}
		UserInfo userInfo = userInfoService.get(userinfoId);
		if (userInfo == null) {
			errorCode = 1;
			errorMessage = "没有用户信息";
		}

		if (!file.isEmpty()) {
			String basePath = "upload";
			// 文件的目录名
			String dirName = "images";
			// 文件保存目录路径
			String savePath = request.getSession().getServletContext().getRealPath("/") + basePath + File.separator
					+ dirName + File.separator + DateUtils.getYear() + File.separator + DateUtils.getMonth()
					+ File.separator + DateUtils.getDay();

			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			String fileName = file.getOriginalFilename();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			try {
				File uploadedFile = new File(savePath, newFileName);
				file.transferTo(uploadedFile);
				errorMessage = "上传成功";
				errorCode = 0;
				String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/"
						+ request.getContextPath() + "/" + basePath + "/" + dirName + "/" + DateUtils.getYear() + "/"+ DateUtils.getMonth()
						+ "/"+ DateUtils.getDay()+ "/" + newFileName;// 相对路径，app需要拼接地址
				// String url =
				// request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+uploadedFile.getAbsolutePath();
				data.put("url", url);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				errorCode = 1;
				errorMessage = "文件上传异常";
			}
			// 将上传文件保存到一个目标文件当中
		} else {
			errorMessage = "文件为空";
			errorCode = 1;
		}
		jserrorCode.put("errorCode", errorCode);
		jserrorCode.put("errorMessage", errorMessage);
		jserrorCode.put("data", data);
		return jserrorCode.toJSONString();

	}

	/**
	 * 分析图片 返回结果
	 * 
	 * @param userinfoId
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "uploadResult", method = RequestMethod.POST)
	@ResponseBody
	public String uploadImageResult(@RequestParam("userinfoId") String userinfoId, HttpServletRequest request,
			@RequestParam("file") MultipartFile file) {
		String errorMessage = "";
		int errorCode = 0;

		jserrorCode = new JSONObject();
		JSONObject data = new JSONObject();
		if (!StringUtils.isNoneBlank(userinfoId)) {
			errorCode = 1;
			errorMessage = "没有用户ID";
		}
		UserInfo userInfo = userInfoService.get(userinfoId);
		if (userInfo == null) {
			errorCode = 1;
			errorMessage = "没有用户信息";
		}

		if (!file.isEmpty()) {
			String basePath = "upload";
			// 文件的目录名
			String dirName = "images";
			// 文件保存目录路径
			String savePath = request.getSession().getServletContext().getRealPath("/") + basePath + File.separator
					+ dirName + File.separator + DateUtils.getYear() + File.separator + DateUtils.getMonth()
					+ File.separator + DateUtils.getDay();

			File saveDirFile = new File(savePath);
			if (!saveDirFile.exists()) {
				saveDirFile.mkdirs();
			}
			String fileName = file.getOriginalFilename();
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
			try {
				File uploadedFile = new File(savePath, newFileName);
				file.transferTo(uploadedFile);
				errorMessage = "上传成功";
				errorCode = 0;
				String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/"
						+ request.getContextPath() + "/" + basePath + "/" + dirName + "/" + DateUtils.getYear() + "/"+ DateUtils.getMonth()
						+ "/"+ DateUtils.getDay() + "/" + newFileName;// 相对路径，app需要拼接地址
				// String url =
				// request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+uploadedFile.getAbsolutePath();
				data.put("url", url);
				String BDurl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
						+ request.getContextPath() + uploadedFile.getAbsolutePath();
				String val = ImageHeler.analyseRGB(url);
				data.put("val", val);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				errorCode = 1;
				errorMessage = "文件上传异常";
			}
			// 将上传文件保存到一个目标文件当中
		} else {
			errorMessage = "文件为空";
			errorCode = 1;
		}
		jserrorCode.put("errorCode", errorCode);
		jserrorCode.put("errorMessage", errorMessage);
		jserrorCode.put("data", data);
		return jserrorCode.toJSONString();

	}

	/**
	 * 新增反馈意见信息 10074
	 * 
	 * @param signature
	 * 
	 * @return
	 */
	public String feedback_edit(String signature) {
		JSONObject datajson = new JSONObject();
		// 传递过来的数据进行格式化
		JSONObject jsStr = JSONObject.parseObject(signature);
		UserInfo user = new UserInfo();
		// 查询用户名是否注册

		user = userInfoService.get(jsStr.getString("userinfoId"));
		String title = jsStr.getString("title");
		String remark = jsStr.getString("remark");
		GrassFeedback grassFeedback = new GrassFeedback();
		if (user != null) {

			grassFeedback.setUserinfo(user);
			grassFeedback.setTitle(title);
			grassFeedback.setRemark(remark);

			grassFeedbackService.save(grassFeedback);
			// 错误返回信息
			jserrorCode.put("errorCode", 0);
			jserrorCode.put("errorMessage", "添加成功");
			jserrorCode.put("data", datajson);

		} else {
			// 错误返回信息
			jserrorCode.put("errorCode", 1);
			jserrorCode.put("errorMessage", "用户信息有误，错误的用户ID");
			jserrorCode.put("data", datajson);
		}
		return jserrorCode.toString();
	}

	public Object[] arrayTest2(Object[] arr) {
		// 实例化一个set集合
		Set set = new HashSet();
		// 遍历数组并存入集合,如果元素已存在则不会重复存入
		for (int i = 0; i < arr.length; i++) {
			set.add(arr[i]);
		}
		// 返回Set集合的数组形式
		return set.toArray();
	}

	public static void main(String arg[]) {
		String json = "{\"msgtype\":10013,\"remark\":[{\"url\":\"http://epms.fatedog.com:80//grass_manage/upload/images/20180512115607_130.jpg\",\"val\":\"0.3\"},{\"url\":\"http://epms.fatedog.com:80//grass_manage/upload/images/20180512115644_309.jpg\",\"val\":\"0.27\"},{\"url\":\"http://epms.fatedog.com:80//grass_manage/upload/images/20180512115619_615.jpg\",\"val\":\"0.14\"},{\"url\":\"http://epms.fatedog.com:80//grass_manage/upload/images/20180512115658_889.jpg\",\"val\":\"0.16\"},{\"url\":\"http://epms.fatedog.com:80//grass_manage/upload/images/20180512115632_76.jpg\",\"val\":\"0.22\"}],\"log\":111.690891,\"stand8val\":\"\",\"userinfoId\":\"695449239a8a459eaf1ec84088736798\",\"lat\":40.865145,\"avgVal\":\"0.22\",\"grassId\":\"6561de0acb9a4d51b96630ac1236155d\"}";
	}
}
